package com.yungu.swift.api.wxapi.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.yungu.swift.api.wxapi.pojo.SNSUserInfo;
import com.yungu.swift.api.wxapi.pojo.WeixinOauth2Token;
import com.yungu.swift.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * Created by cuixiuyin on 2018/5/3.
 */
@Slf4j
public class AdvancedUtil {

    /**
     * 获取网页授权凭证
     *
     * @param appId     公众账号的唯一标识
     * @param appSecret 公众账号的密钥
     * @param code
     * @return WeixinAouth2Token
     */
    public static WeixinOauth2Token getOauth2AccessToken(String appId, String appSecret, String code) {
        WeixinOauth2Token wat = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        requestUrl = requestUrl.replace("APPID", appId);
        requestUrl = requestUrl.replace("SECRET", appSecret);
        requestUrl = requestUrl.replace("CODE", code);
        // 获取网页授权凭证
        JsonNode jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
        if (null != jsonObject) {
            try {
                wat = new WeixinOauth2Token();
                wat.setAccessToken(jsonObject.get("access_token").asText());
                wat.setExpiresIn(jsonObject.get("expires_in").asInt());
                wat.setRefreshToken(jsonObject.get("refresh_token").asText());
                wat.setOpenId(jsonObject.get("openid").asText());
                wat.setScope(jsonObject.get("scope").asText());
            } catch (Exception e) {
                int errorCode = jsonObject.get("errcode").asInt();
                String errorMsg = jsonObject.get("errmsg").asText();
                log.error("获取网页授权凭证失败 errcode:{" + errorCode + "} errmsg:{" + errorMsg + "}");
                wat = new WeixinOauth2Token();
                wat.setErrorCode(errorCode);
            }
        }
        return wat;
    }

    /**
     * 通过网页授权获取用户信息
     *
     * @param accessToken 网页授权接口调用凭证
     * @param openId      用户标识
     * @return SNSUserInfo
     */
    @SuppressWarnings({"deprecation", "unchecked"})
    public static SNSUserInfo getSNSUserInfo(String accessToken, String openId) {
        SNSUserInfo snsUserInfo = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        // 通过网页授权获取用户信息
        JsonNode jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                snsUserInfo = new SNSUserInfo();
                // 用户的标识
                snsUserInfo.setOpenId(jsonObject.get("openid").asText());
                // 昵称
                snsUserInfo.setNickname(jsonObject.get("nickname").asText());
                // 性别（1是男性，2是女性，0是未知）
                snsUserInfo.setSex(jsonObject.get("sex").asInt());
                // 用户所在国家
                snsUserInfo.setCountry(jsonObject.get("country").asText());
                // 用户所在省份
                snsUserInfo.setProvince(jsonObject.get("province").asText());
                // 用户所在城市
                snsUserInfo.setCity(jsonObject.get("city").asText());
                // 用户头像
                snsUserInfo.setHeadImgUrl(jsonObject.get("headimgurl").asText());
                // 用户特权信息
                snsUserInfo.setPrivilegeList(JsonUtils.readValue(jsonObject.get("privilege").toString(), List.class));
            } catch (Exception e) {
                snsUserInfo = null;
                int errorCode = jsonObject.get("errcode").asInt();
                String errorMsg = jsonObject.get("errmsg").asText();
                log.error("获取用户信息失败 errcode:{" + errorCode + "} errmsg:{" + errorMsg + "}");
            }
        }
        return snsUserInfo;
    }
}
